<template>
  <div>
    <el-form ref="myform" :model="formItem" :rules="rules" label-width="100px" size="mini">
      <el-row :gutter="40">
        <el-col :span="8">
          <el-form-item label="通知名称" prop="name">
            <el-input v-model="formItem.name" placeholder="请输入通知名称" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="服务停止时间" prop="stopTime">
            <el-date-picker
              v-model="formItem.stopTime"
              type="datetime"
              placeholder="选择日期时间"
              align="right"
              :picker-options="pickerOptions"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="维护部门" prop="orgCode">
            <treeselect
              v-model="formItem.orgCode"
              :multiple="false"
              :options="availableOganizations"
              placeholder="请选择部门"
              @select="selcetOrg"
              @input="inputOrg"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="40">
        <el-col :span="8">
          <el-form-item label="维护地点" prop="location">
            <el-input v-model="formItem.location" placeholder="请输入维护地点" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="维护开始时间" prop="startDateTime">
            <el-date-picker
              v-model="formItem.startDateTime"
              type="datetime"
              placeholder="选择日期时间"
              align="right"
              :picker-options="pickerOptions"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="维护结束时间" prop="endDateTime">
            <el-date-picker
              v-model="formItem.endDateTime"
              type="datetime"
              placeholder="选择日期时间"
              align="right"
              :picker-options="pickerOptions"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="40">
        <el-col :span="8">
          <el-form-item label="维护类别" prop="modelCode">
            <treeselect
              v-model="formItem.modelCode"
              :multiple="false"
              :options="cmdbModels"
              :load-options="loadOptions"
              :disable-branch-nodes="true"
              id-key="code"
              label-key="name"
              placeholder="请选择维护类别"
              @select="selModel"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="通知方式" prop="noticeType">
            <el-select v-model="formItem.noticeType" multiple class="select_input" placeholder="请选择通知方式">
              <el-option v-for="(item) in notices" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="40">
        <el-col :span="24">
          <el-form-item label="维护对象" prop="instancesArray">
            <div style="margin-bottom: 5px;">
              <el-button type="primary" size="mini" icon="el-icon-plus" @click="handleSelectInstances">添加</el-button>
              <el-button type="primary" size="mini" icon="el-icon-delete" @click="handleRemove">移除</el-button>
            </div>
            <div class="anthor-info-body">
              <div class="table-app-container">
                <div class="fixed-table">
                  <PageableTable
                    :data="formItem.instancesArray"
                    :loading="false"
                    :table-height="160"
                    :disable-pageable="true"
                    :multiple-selected="true"
                    class="fixed-table-table"
                    @selection-change="tableSelection"
                  >
                    <el-table-column v-for="column in insideColumns" :key="column.key" :label="column.title" :prop="column.key" :width="column.width" :sortable="column.sortable">
                      <template slot-scope="scope">
                        <column-render :render="column.render" :row="scope.row" :column="column" />
                      </template>
                    </el-table-column>
                  </PageableTable>
                </div>
              </div>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="40">
        <el-col :span="24">
          <el-form-item label="通知人" prop="users">
            <el-input placeholder="请选择通知人" @focus="handleUserIconClick" />
            <div v-if="formItem.users.length > 0" class="fix-input-prefix2">
              <el-tag v-for="tag in formItem.users" :key="tag.name" size="mini" closable type="success" @close="removeUser(tag)">{{ tag.name }}</el-tag>
              <i class="el-icon-close" title="清除所有值" @click="clearAllUser" />
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="40">
        <el-col :span="12">
          <el-form-item label="维护内容">
            <el-input v-model="formItem.content" placeholder="请输入维护内容" type="textarea" :rows="3" :autosize="true" resize="none" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="影响及保障措施">
            <el-input v-model="formItem.impactSafeguard" placeholder="请输入影响及保障措施" type="textarea" :rows="3" :autosize="true" resize="none" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="40">
        <el-col :span="12">
          <el-form-item label="其他影响情况">
            <el-input v-model="formItem.others" placeholder="请输入其他影响情况" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <SelectDialog title="选择执行人" :append-to-body="true" :show="userSelDialogFormVisible" @on-ok="selectUserOk" @on-cancel="selectUserCancel">
      <UsersPage ref="usersTable" :for-selection="true" :multiple-selected="true" />
    </SelectDialog>
    <SelectDialog v-if="instanceSelDialogFormVisible" title="选择维护对象" width="60%" :append-to-body="true" :show="instanceSelDialogFormVisible" @on-ok="selectInstanceOk" @on-cancel="selectInstanceCancel">
      <instancesTable ref="instancesTable" :for-selection="true" :model-code="formItem.modelCode" :multiple-selected="true" />
    </SelectDialog>
  </div>
</template>

<script>
import Vue from 'vue'
import { formatDate } from '@neu/biz-core/utils/utils'
import {
  create,
  update,
  detail
} from '@neu/dcom-ui/api/stopServiceNotice'
import * as organizations from '@neu/auth-ui/api/organization'
import { pureTree } from '@neu/dcom-ui/api/schema'
import instancesTable from '@neu/dcom-ui/views/instances/tables'
import SelectDialog from '@neu/biz-core/components/SelectDialog'
import UsersPage from '@neu/auth-ui/views/users/tables'
import PageableTable from '@neu/biz-core/components/PageableTable'

const formItem = {
  name: '',
  code: '',
  orgCode: null,
  orgName: '',
  modelCode: null,
  modelName: null,
  status: 'unsend',
  stopTime: '',
  location: '',
  startDateTime: '',
  endDateTime: '',
  jsonUsers: '',
  userNames: '',
  objNames: '',
  users: [],
  noticeType: [],
  others: '',
  impactSafeguard: '',
  content: '',
  instancesArray: [],
  jsonObjs: ''
}
export default {
  name: 'StopServiceNoticeEditForm',
  components: {
    UsersPage,
    SelectDialog,
    PageableTable,
    instancesTable
  },
  props: {
    id: {
      required: false,
      type: Number,
      default: -1
    }
  },
  data() {
    return {
      /** CMDB模型树 */
      cmdbModels: null,
      /** CMDB实例 */
      cmdbInstances: null,
      /** 是否显示用户选择对话框 */
      userSelDialogFormVisible: false,
      /** 部门 */
      availableOganizations: [],
      /** 是否显示实例 */
      instanceSelDialogFormVisible: false,
      /** 通知方式 */
      notices: [{ value: 'notice', label: '系统通知' }, { value: 'message', label: '短信' }, { value: 'email', label: '邮件' }],
      /** 要移除的对象 */
      removeData: [],
      // 编辑的表单内容
      formItem: {
        ...formItem
      },
      insideColumns: [
        // { title: 'ID', key: '_id' },
        { title: '唯一标识', key: 'code' },
        { title: '名称', key: 'name' }
        // { title: '模型', key: 'schemadefName' }
      ],
      /** 是否初始化 */
      isUpdateInit: true,
      // 表单验证规则
      rules: {
        name: [{
          required: true,
          message: '通知名称不能为空',
          trigger: 'blur'
        }],
        orgCode: [{
          required: true,
          message: '维护部门不能为空',
          trigger: 'blur'
        }],
        location: [{
          required: true,
          message: '维护地点不能为空',
          trigger: 'blur'
        }],
        objName: [{
          required: true,
          message: '维护对象不能为空',
          trigger: 'blur'
        }],
        noticeType: [{
          required: true,
          message: '通知方式不能为空',
          trigger: 'blur'
        }],
        instancesArray: [{
          required: true,
          message: '维护对象不能为空',
          trigger: 'blur'
        }],
        users: [{ required: true, type: 'array', message: '通知人不能为空', trigger: 'change' }],
        modelCode: [{
          required: true,
          message: '维护类别不能为空',
          trigger: 'blur'
        }],
        stopTime: [{
          required: true,
          message: '停止时间不能为空',
          trigger: 'blur'
        }],
        startDateTime: [{
          required: true,
          message: '开始时间不能为空',
          trigger: 'blur'
        }],
        endDateTime: [{
          required: true,
          message: '结束时间不能为空',
          trigger: 'blur'
        }]
      },
      dialogViewRuleVisible: false,
      pickerOptions: {
        disabledDate(date) {
          return date.getTime() <= Date.now()
        },
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date())
          }
        }, {
          text: '昨天',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24)
            picker.$emit('pick', date)
          }
        }, {
          text: '一周前',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', date)
          }
        }]
      }
    }
  },
  watch: {
    id: function() {
      this.fetch()
    }
  },
  created() {
    this.fetch()
    organizations.tree().then(response => {
      this.availableOganizations = [response.data]
    })
  },
  methods: {
    fetch() {
      if (this.id !== -1) {
        detail(this.id).then(response => {
          this.isUpdateInit = false
          this.formItem = {
            ...response.data
          }
          this.formItem.instancesArray = JSON.parse(this.formItem.jsonObjs)
        })
      } else {
        this.formItem = {
          ...formItem
        }
        this.formItem.users = []
      }
    },
    save() {
      const updated = this.id !== -1
      return new Promise(resolve => {
        this.$refs.myform.validate((valid) => {
          if (valid) {
            this.formItem.jsonObjs = JSON.stringify(this.formItem.instancesArray)
            this.formItem.jsonUsers = JSON.stringify(this.formItem.users)

            // if (formatDate(this.formItem.stopTime) > formatDate(this.formItem.startDateTime)) {
            //   return this.$message({
            //     showClose: true,
            //     message: '停止服务时间不能大于维护结束时间',
            //     type: 'error'
            //   })
            // }

            if (formatDate(this.formItem.startDateTime) > formatDate(this.formItem.endDateTime)) {
              return this.$message({
                showClose: true,
                message: '维护开始时间不能大于维护结束时间',
                type: 'error'
              })
            }

            if (this.formItem.others !== null && this.formItem.others.length > 255) {
              return this.$message({
                showClose: true,
                message: '其他影响情况不能超过255个字符',
                type: 'error'
              })
            }

            if (updated) {
              resolve(update(this.id, this.formItem))
            } else {
              resolve(create(this.formItem))
            }
          } else {
            resolve(false)
          }
        })
      })
    },
    reset() {
      this.$refs.myform.resetFields()
      this.formItem.users = []
      this.formItem.instancesArray = []
      this.formItem.noticeType = []
      this.formItem = { ...formItem }
    },
    handleSelectInstances() {
      if (!this.formItem.modelCode) {
        this.$message({
          type: 'warning',
          message: '请选择维护类别'
        })
        return
      }
      this.instanceSelDialogFormVisible = true
    },
    handleRemove() {
      if (this.removeData.length === 0) {
        return this.$message({
          showClose: true,
          message: '请选择一个对象',
          type: 'error'
        })
      }

      this.removeData.forEach(t => {
        this.formItem.instancesArray.forEach((item, index) => {
          if (item.code === t) {
            Vue.delete(this.formItem.instancesArray, index)
          }
        })
      })
    },
    tableSelection(sel) {
      this.removeData = sel.map(a => a.code)
    },
    selectInstanceOk() {
      const instances = this.$refs.instancesTable.selections
      const instanceCodes = this.formItem.instancesArray.map(a => a.code)
      const difference = instances.filter(t => {
        return !instanceCodes.includes(t.code)
      })
      this.formItem.instancesArray.push(...difference)
      this.instanceSelDialogFormVisible = false
    },
    selectInstanceCancel() {
      this.instanceSelDialogFormVisible = false
    },
    loadOptions({ action }) {
      if (action === 'LOAD_ROOT_OPTIONS') {
        return pureTree().then(response => {
          this.cmdbModels = response.data
        })
      }
    },
    handleUserIconClick() {
      this.userSelDialogFormVisible = true
    },
    selModel(node) {
      if (this.formItem.modelCode !== node.code) {
        this.formItem.instancesArray = []
      }
      this.formItem.modelName = node.name
      this.formItem.modelCode = node.code
    },
    selcetOrg(value) {
      this.formItem.orgName = value.title
    },
    inputOrg(value) {
      if (this.isUpdateInit) {
        this.formItem.userId = ''
        this.formItem.userName = ''
      }
      this.isUpdateInit = true
      if (value === undefined) {
        this.formItem.orgName = ''
      }
    },
    selectUserOk() {
      var usersSel = this.$refs.usersTable.selections
      var currentUserIds = this.formItem.users.map(user => user.id)
      var difference = usersSel.filter(t => {
        return !currentUserIds.includes(t.id)
      })
      difference.forEach(t => {
        const user = { id: t.id, name: t.name, username: t.username }
        this.formItem.users.push(user)
      })

      this.userSelDialogFormVisible = false
    },
    selectUserCancel() {
      this.userSelDialogFormVisible = false
    },
    removeUser(tag) {
      this.formItem.users.splice(this.formItem.users.indexOf(tag), 1)
    },
    /** 删除所有项 */
    clearAllUser() {
      this.formItem.users = []
    }
  }

}
</script>
